#include "Enemy.h"
#include "EnemyBullet.h"

bool Enemy::init()
{
	if (!CCNode::init() )
	{
		return false;
	}
	this->setAnchorPoint(ccp(0.5, 0.5));

	CCSpriteFrame* dogFrame1 = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("enemy_other_2.png");

	m_dog = CCSprite::createWithSpriteFrame(dogFrame1);
	CCSize size = m_dog->getContentSize();
	this->setContentSize(size);
	m_dog->setPosition(ccp(size.width / 2, size.height / 2));
	this->addChild(m_dog);
	m_dog->retain();

	m_die_dog = CCSprite::create("boom1.png");
	m_die_dog->setScale(0.5);
	m_die_dog->setPosition(ccp(size.width / 2, size.height / 2));
	this->addChild(m_die_dog);
	m_die_dog->retain();
	m_die_dog->setVisible(false);

	m_enemyBullets = CCArray::createWithCapacity(20);
	for (unsigned int i = 0; i < m_enemyBullets->capacity(); i++ )
	{
		EnemyBullet* enemyBullet = EnemyBullet::create();
		m_enemyBullets->addObject(enemyBullet);
	}
	m_enemyBullets->retain();


	return true;
}

Enemy::Enemy() :m_dog(NULL), m_die_dog(NULL), m_life(false), m_id(0), m_enemyBullets(NULL)
{

}

Enemy::~Enemy()
{
	m_dog->release();
	m_die_dog->release();
	if (m_enemyBullets)
	{
		m_enemyBullets->release();
	}
}

void Enemy::setDie()
{
	m_life = false;
	m_dog->setVisible(false);
	
	this->stopAllActions();
	CCAnimation* animation = CCAnimation::create();
	animation->addSpriteFrameWithFileName("boom1.png");
	animation->addSpriteFrameWithFileName("boom2.png");
	animation->addSpriteFrameWithFileName("boom3.png");
	animation->addSpriteFrameWithFileName("boom4.png");
	animation->addSpriteFrameWithFileName("boom5.png");
	animation->setDelayPerUnit(0.3f);

	CCLog( "[setDie] id:%d,x:%f,y:%f", m_id,  this->getPosition().x, this->getPosition().y);
	m_die_dog->setVisible(true);
	m_die_dog->runAction(CCSequence::create(CCRepeat::create(CCAnimate::create(animation), 1), CCCallFuncN::create( this, callfuncN_selector(Enemy::reLife)),NULL));


}

void Enemy::reLife(CCNode* pSender)
{
	//m_dog->setVisible(true);
	//m_die_dog->setVisible(false);
	m_life = false;
	m_dog->setVisible(false);
	m_die_dog->setVisible(false);
	CCLog("[reLife] id:%d,x:%f,y:%f", m_id, this->getPosition().x, this->getPosition().y);

	this->stopAllActions();
}

void Enemy::move(const CCPoint& heroPoint)
{
	CCSize size = CCDirector::sharedDirector()->getWinSize();
	int posX = rand() % 10;
	this->setPosition(ccp( posX*30, size.height ));
	//this->runAction(CCSequence::create(CCMoveTo::create(abs(size.height) / 130, ccp(heroPoint.x, 0)), CCCallFuncN::create(this, callfuncN_selector(Enemy::reLife)), NULL));
	this->runAction(CCSequence::create(CCMoveTo::create(abs(size.height) / 130, ccp(posX * 30, 0)), CCCallFuncN::create(this, callfuncN_selector(Enemy::reLife)), NULL));
}

void Enemy::setDogShow(bool val)
{
	if (!m_dog)
	{
		return;
	}
	m_dog->setVisible(val);
}
